package cn.jc.myfile.common.validation;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 校验工具
 */

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ValidatorUtils {

    /** 校验器列表 **/
    private final List<cn.jc.myfile.common.validation.Validator> validatorList;

    public void validate(Object target) {
        Class<?> targetClass = target.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            Annotation[] filedAnnotations = field.getAnnotations();
            if (filedAnnotations.length > 0) {
                for (int i = 0; i < filedAnnotations.length; i++) {
                    Annotation annotation = filedAnnotations[i];
                    Class annotationType = annotation.annotationType();
                    validatorList.forEach(validator -> {
                        if (validator.supportAnnotation().equals(annotationType)) {
                            validator.validate(target, field, annotation);
                        }
                    });
                }
            }
        }
    }
}
